package com.lst.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lst.api.constant.DeleteEnum;
import com.lst.api.entity.LoanInfo;
import com.lst.api.entity.WorkCompanyInfo;
import com.lst.api.mapper.LoanInfoMapper;
import com.lst.api.service.ILoanInfoService;
import com.lst.api.vo.LoanInfoVo;
import com.lst.tools.mybatis.service.impl.BaseService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 贷款信息表业务层实现
 *
 * @author Frank
 * @date 2019-12-30 10:31:37
 * @version: V1.0
 */
@Service
public class LoanInfoService extends BaseService<LoanInfoMapper, LoanInfo> implements ILoanInfoService {

    @Override
    public boolean saveOrUpdate(long userId, String applyNo, List<LoanInfoVo> loanInfoVoList) {
        if (CollectionUtils.isEmpty(loanInfoVoList)) {
            return false;
        }
        List<LoanInfo> loanInfoList = new ArrayList<>();
        for (LoanInfoVo loanInfoVo : loanInfoVoList) {
            if (loanInfoVo.isAllFieldNull()) {
                continue;
            }
            loanInfoVo.check();
            LoanInfo loanInfo = new LoanInfo(userId, applyNo, loanInfoVo);
            loanInfoList.add(loanInfo);
        }
        if (CollectionUtils.isEmpty(loanInfoList)) {
            return false;
        }
        UpdateWrapper<LoanInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq(WorkCompanyInfo.APPLY_NO, applyNo)
                .eq(WorkCompanyInfo.PROMO_USER_ID, userId)
                .set(WorkCompanyInfo.IS_DELETE, DeleteEnum.DELETE_YES.getKey());
        super.update(updateWrapper);
        return super.saveBatch(loanInfoList);
    }

    @Override
    public List<LoanInfo> listByApplyNo(String applyNo) {
        QueryWrapper<LoanInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(LoanInfo.APPLY_NO, applyNo)
                .eq(LoanInfo.IS_DELETE, DeleteEnum.DELETE_NO.getKey())
                .orderByAsc(LoanInfo.CREATE_AT);
        return super.list(queryWrapper);
    }
}